package amazon

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/dchest/uniuri"
	"math/rand"
	"regexp"
	"strings"
)

// 获取cc表单
func (a *Amazon) GetCreditCardForm(document *goquery.Document) (newDocument *goquery.Document, err error) {
	html, _ := document.Html()
	//matcher := regexp.MustCompile(`"secureFormTarget":"(ApxSecureIframe-pp-[\w]+-[\d]+)"`)
	//matchResult := matcher.FindAllStringSubmatch(html, -1)
	//var frameName string
	//if len(matchResult) > 0 {
	//	frameName = matchResult[0][1]
	//}
	//
	//matcher = regexp.MustCompile(`"parentWidgetInstanceId":"([\w]+)"`)
	//matchResult = matcher.FindAllStringSubmatch(html, -1)
	//var parentWidgetInstanceId string
	//if len(matchResult) > 0 {
	//	parentWidgetInstanceId = matchResult[0][1]
	//}

	//widgetState, _ :=  document.Find("input[name='ppw-widgetState']").Attr("value")
	var widgetState string
	matcher := regexp.MustCompile(`"serializedState":"([^"]+)"`)
	matchResult := matcher.FindAllStringSubmatch(html, -1)
	if len(matchResult) > 0 {
		widgetState = matchResult[0][1]
	}
	paymentInfo := map[string]string{
		"widgetState": widgetState,
		"returnUrl":   "/gp/buy/payselect/handlers/apx-submit-continue.html",
		"clientId":    "YA:Wallet", //1
		//"clientId":"Checkout", //1
		"usePopover":                     "true",
		"maxAgeSeconds":                  "7200",
		"iFrameName":                     fmt.Sprintf(`ApxSecureIframe-pp-%s-%d`, uniuri.NewLen(6), rand.Int()),
		"parentWidgetInstanceId":         uniuri.NewLen(12),
		"hideAddPaymentInstrumentHeader": "true",
		"creatablePaymentMethods":        "CC",
	}

	_, newDocument, err = a.Submit(`https://apx-security.amazon.com/cpe/pm/register`, POST, nil, nil, paymentInfo)

	return
}

// 提交cc表单
func (a *Amazon) CreateCreditCard(recipient, cardNo, valid string, document *goquery.Document) (newDocument *goquery.Document, err error) {
	action, method, paymentFormData, err := a.ExtractFormData(document, "form[id^='pp-']")
	if err != nil {
		return nil, err
	}

	html, _ := document.Html()
	var customerId string
	matcher := regexp.MustCompile(`"customerId":"([^"]+)"`)
	matchResult := matcher.FindAllStringSubmatch(html, -1)
	if len(matchResult) > 0 {
		customerId = matchResult[0][1]
	}

	validDate := strings.Split(valid, "/")
	paymentFormData["addCreditCardNumber"] = cardNo
	//paymentFormData["addCreditCardNumber"] = creditCard.CardNo
	paymentFormData["ppw-accountHolderName"] = recipient
	paymentFormData["ppw-expirationDate_month"] = validDate[0]
	paymentFormData["ppw-expirationDate_year"] = validDate[1]

	paymentFormData["ppw-jsEnabled"] = "true"

	//action = fmt.Sprintf(`https://apx-security.amazon.com/payments-portal/data/f1/widgets2/v1/customer/%s/continueWidget?sif_profile=APX-Encrypt-All-NA`, customerId)
	action = fmt.Sprintf(`https://apx-security.amazon.com/payments-portal/data/widgets2/v1/customer/%s/continueWidget?sif_profile=APX-Encrypt-All-NA`, customerId)
	_, newDocument, err = a.Submit(action, method, nil, nil, paymentFormData)

	return
}

// 设置为默认的信用卡支付
func (a *Amazon) SetDefaultCreditCard(document *goquery.Document) (newDocument *goquery.Document, err error) {
	action, method, formData, err := a.ExtractFormData(document, "form")
	if err != nil {
		return nil, err
	}

	html, _ := document.Html()

	html = strings.ReplaceAll(html, `\&#34;`, "")
	html = strings.ReplaceAll(html, `&#34;`, "")
	html = strings.ReplaceAll(html, `\n`, "")
	html = strings.ReplaceAll(html, `\"`, `"`)

	var customerId string
	matcher := regexp.MustCompile(`"customerId":"([^"]+)"`)
	matchResult := matcher.FindAllStringSubmatch(html, -1)
	if len(matchResult) > 0 {
		customerId = matchResult[0][1]
	}

	document, _ = goquery.NewDocumentFromReader(strings.NewReader(html))

	action = fmt.Sprintf(`https://apx-security.amazon.com/payments-portal/data/widgets2/v1/customer/%s/continueWidget`, customerId)
	_, newDocument, err = a.Submit(action, method, nil, nil, map[string]string{
		"ppw-jsEnabled":   "true",
		"ppw-widgetState": formData["ppw-widgetState"],
		"ppw-widgetEvent:SavePaymentMethodDetailsEvent": "",
		"ie":                                "UTF-8",
		"ppw-updateEverywhereAddCreditCard": "updateEverywhereAddCreditCard",
	})

	return
}
